package com.kaili.basic.controller.web.v1;

import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.basic.mapper.BaseCompanyMapper;
import com.kaili.basic.pojo.dto.BaseCompanyAddDto;
import com.kaili.basic.pojo.dto.BaseCompanyQueryDto;
import com.kaili.basic.pojo.entity.BaseCompany;
import com.kaili.basic.pojo.entity.BaseProduct;
import com.kaili.basic.service.BaseUserService;
import com.kaili.basic.service.IBaseCompanyService;
import com.kaili.basic.version.ApiVersion;
import com.kaili.common.entity.BaseUser;
import com.kaili.common.response.CommonStatus;
import com.kaili.common.response.RestStatus;
import com.kaili.common.tenant.DbContextHolder;
import com.kaili.common.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 前端控制器
 *
 * @author fzj
 * @since 2018-05-09
 */
@ApiVersion(1)
@RequestMapping("/{api_version}")
@Api(tags = "物流公司管理", description = "物流公司管理相关API")
@RestController
public class BaseCompanyController {

    @Autowired
    IBaseCompanyService baseCompanyService;
    @Autowired
    AsyncUtils asyncUtils;
    @Autowired
    BaseCompanyMapper baseCompanyMapper;
    @Autowired
    BaseUserService baseUserService;

    /**
     * 新增组户的写库地址
     */
    @Value("${spring.datasource.url.write}")
    private String writeUrl;

    /**
     * 新增组户的读库地址
     */
    @Value("${spring.datasource.url.read}")
    private String readUrl;

    /**
     * 新增组户的数据库用户
     */
    @Value("${spring.datasource.username}")
    private String dbUsername;

    /**
     * 新增组户的数据库密码
     */
    @Value("${spring.datasource.password}")
    private String dbPassword;

    @ApiOperation(value = "新增公司", notes = "新增公司")
    @PostMapping("/companys")
    public RestStatus addBaseCompany(@RequestBody BaseCompanyAddDto dto) {
        BaseCompany company = new BaseCompany();
        BeanUtils.copyProperties(dto,company);

        Long createBy = LoginDetailUtils.getCurrentEmployeeId().longValue();
        company.setCreateBy(createBy);
        company.setCreateTime(new Date());
        if (StringUtils.isEmpty(company.getUrl())) {
            company.setUrl(baseCompanyService.getImgByKey("logo"));
        }
        int i = baseCompanyService.addBaseCompany(company);
        if (i == 7||i== 8) {
            return CommonStatus.ADD_DEFEAT;
        }
        Map map = new HashMap();

        String dbName = "db" + company.getCompanyId();
        map.put("writeUrl", writeUrl + dbName + "?useUnicode=true&characterEncoding=UTF8");
        map.put("readUrl", readUrl + dbName + "?useUnicode=true&characterEncoding=UTF8");
        map.put("dbName", dbName);
        map.put("dbUsername", dbUsername);
        map.put("dbPassword", dbPassword);
        map.put("companyCode", company.getCompanyId().toString());
        map.put("companyName", company.getCompanyName());
        map.put("companyPY", PinYinUtil.toPinYin(company.getCompanyName()));
        map.put("phone", company.getPhoneNumber());
        map.put("username", company.getUsername());
        String pwd = company.getPassword();//密码
        String npwd = company.getPassword();//用来循环的密码；
        String encode = hexpwd(pwd, npwd);//加密后16进制的密码;
        map.put("password", encode);
        asyncUtils.createDbAndOthers(map);
        return CommonStatus.ADD_OK;
    }

    @ApiOperation(value = "更新公司", notes = "更新公司")
    @PutMapping("/companys")
    public RestStatus updateBaseCompany(@RequestBody BaseCompanyAddDto dto) {
        BaseCompany company = new BaseCompany();
        BeanUtils.copyProperties(dto,company);

        company.setModifyBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
        company.setModifyTime(new Date());
        if (baseCompanyService.updateBaseCompany(company) == -1) {
        }

        DbContextHolder.setDbType(company.getCompanyId() + "_write");
        BaseUser baseUser = new BaseUser();
        baseUser.setUsername(company.getUsername());
        String pwd = company.getPassword();//密码
        String npwd = company.getPassword();//用来循环的密码；
        String encode = hexpwd(pwd, npwd);//加密后16进制的密码;
        baseUser.setPassword(encode);
        baseUser.setId(1);
        baseUserService.updateBaseUser(baseUser);
        return CommonStatus.UPDATE_OK;
    }

    @ApiOperation(value = "删除公司", notes = "删除公司")
    @DeleteMapping("/companys/{companyId}")
    public RestStatus deleteBaseCompany(@PathVariable("companyId") @ApiParam(value = "PDA的SN") Integer companyId) {
        BaseCompany company = new BaseCompany();
        company.setCompanyId(companyId);
        company.setModifyBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
        company.setModifyTime(new Date());
        if (baseCompanyService.deleteBaseCompany(company) == -1) {

        }
        return CommonStatus.DELETE_OK;
    }

    @ApiOperation(value = "分页查询公司信息", notes = "分页查询公司信息")
    @GetMapping("/companys")
    public Page<BaseCompany> getBaseCompanyByKeywords(@ModelAttribute BaseCompanyQueryDto dto) {
        Page<BaseCompany> page = baseCompanyService.getBaseCompanyByKeywords(new Page<BaseCompany>(dto.getPage(), dto.getPageSize()), dto);
        List<BaseCompany> baseCompanys = page.getRecords();
        if (baseCompanys != null && baseCompanys.size() > 0) {
            for (int i = 0; i < baseCompanys.size(); i++) {
                BaseCompany bean = baseCompanys.get(i);
                String currentDbType = DbContextHolder.getDbType();
                try{
                    //查询数据(最大货物量)
                    DbContextHolder.setDbType(bean.getCompanyCode()+"_read");
                    Double weight=baseCompanyMapper.getMaxWeight();
                    DbContextHolder.setDbType(currentDbType);
                    if (weight == null) {
                        bean.setHighVolume(0.00);
                    } else {
                        bean.setHighVolume(weight / 1000);
                    }
                    // 查询数据(最大用户数)
                    DbContextHolder.setDbType(bean.getCompanyCode() + "_read");
                    Integer userCount = baseCompanyMapper.getMaxUser();
                    DbContextHolder.setDbType(currentDbType);
                    bean.setUsedCount(userCount - 1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return page;
    }

    @ApiOperation(value = "查询公司最大编号", notes = "查询公司最大编号")
    @GetMapping("/companys/companyCode")
    public Integer getBaseCompanyCode() {
        List<BaseCompany> list = baseCompanyService.getCompanyCode();
        return list.get(0).getCompanyCode() + 1;
    }

    @ApiOperation(value = "查询所有产品", notes = "查询所有产品")
    @GetMapping("/companys/products")
    public List<BaseProduct> getBaseProduct() {
        return baseCompanyService.getBaseProduct();
    }

    @ApiOperation(value = "根据公司编码查询公司信息", notes = "根据公司编码查询公司信息")
    @GetMapping("/companys/{companyId}")
    public BaseCompany getCompanyUrl(@PathVariable("companyId") @ApiParam(value = "公司编号") Long companyId) {
        String currentDbType = DbContextHolder.getDbType();
        DbContextHolder.setDbType(CommonConstant.MAIN_DB_READ);
        BaseCompany baseCompany = baseCompanyService.getCompanyUrl(companyId);
        DbContextHolder.setDbType(currentDbType);

        return baseCompany;
    }

    @ApiOperation(value = "根据公司编码查询公司URL", notes = "根据公司编码查询公司URL")
    @GetMapping("/companys/url")
    public String getCompanyLogo(@RequestParam("companyId") @ApiParam(value = "公司编号") Long companyId) {
        String currentDbType = DbContextHolder.getDbType();
        DbContextHolder.setDbType(CommonConstant.MAIN_DB_READ);
        BaseCompany baseCompany = baseCompanyService.getCompanyUrl(companyId);
        DbContextHolder.setDbType(currentDbType);
        if (StringUtils.isEmpty(baseCompany.getUrl())) {
            baseCompany.setUrl(baseCompanyService.getImgByKey("logo"));
        }
        return baseCompany.getUrl();
    }

    /**
     * 获取最大用户数和目前最大货量
     *
     * @param companyId
     * @return
     */
    public Map<String, Object> getMaxUserAndMaxWeight(String companyId){
        Map<String,Object> result = new HashMap<>();
        String currentDbType = DbContextHolder.getDbType();
        DbContextHolder.setDbType(companyId+"_read");
        //查询数据

        DbContextHolder.setDbType(currentDbType);

        return result;
    }

    @ApiOperation(value = "注册公司", notes = "注册公司")
    @PostMapping("/companys/register")
    public Map addRegisterCompany(@RequestBody BaseCompanyAddDto dto) {
        BaseCompany company = new BaseCompany();
        BeanUtils.copyProperties(dto,company);

        //判断手机号是否已经注册,一个手机号 只能注册一次
        DbContextHolder.setDbType(CommonConstant.MAIN_DB_WRITE);
        Integer count = baseCompanyService.selectPhone(company.getPhoneNumber());
        if (count > 0) {
            Map map = new HashMap();
            map.put("status", "9");
            map.put("message", "该手机号码已经注册,不能重复注册");
            return map;
        }
        //判断验证码是否有效
        String VerifyCode = baseCompanyService.getVerifyCode(company.getPhoneNumber());
        if (StringUtils.isNotEmpty(VerifyCode)) {
            if (VerifyCode.equals(company.getVerifyCode())) {

            } else {
                Map map = new HashMap();
                map.put("status", "9");
                map.put("message", "验证码无效,请重新输入");
                return map;
            }
        } else {
            Map map = new HashMap();
            map.put("status", "9");
            map.put("message", "验证码无效,请重新输入");
            return map;
        }
        //公司编号
        Integer companyCode = getBaseCompanyCode();
        company.setCompanyCode(companyCode);
        company.setCompanyId(companyCode);
        company.setUserCount(10);
        company.setPassword("123456");
        company.setUsername(company.getPhoneNumber());
        company.setMaxVolume(10);
        company.setCreateBy(-1L);
        company.setCompanySlogan("欢迎使用凯立中小物流平台");
        company.setCreateTime(new Date());
        company.setProductId(1L);
        if (StringUtils.isEmpty(company.getUrl())) {
            company.setUrl(baseCompanyService.getImgByKey("logo"));
        }
        int i = baseCompanyService.addBaseCompany(company);
        if (i == 7) {
            Map map = new HashMap();
            map.put("status", "9");
            map.put("message", "公司重复创建");
            return map;
        }
        if (i == 8) {
            Map map = new HashMap();
            map.put("status", "9");
            map.put("message", "公司创建失败,请联系管理员!!!");
            return map;
        }
        Map map = new HashMap();

        String dbName = "db" + company.getCompanyId();
        map.put("writeUrl", writeUrl + dbName + "?useUnicode=true&characterEncoding=UTF8");
        map.put("readUrl", readUrl + dbName + "?useUnicode=true&characterEncoding=UTF8");
        map.put("dbName", dbName);
        map.put("dbUsername", dbUsername);
        map.put("dbPassword", dbPassword);
        map.put("companyCode", company.getCompanyId().toString());
        map.put("companyName", company.getCompanyName());
        map.put("companyPY", PinYinUtil.toPinYin(company.getCompanyName()));
        map.put("phone", company.getPhoneNumber());
        map.put("username", company.getUsername());
        String pwd = company.getPassword();//密码
        String npwd = company.getPassword();//用来循环的密码；
        String encode = hexpwd(pwd, npwd);//加密后16进制的密码;
        map.put("password", encode);
        asyncUtils.createDbAndOthers(map);
        Map map2 = new HashMap();
        map2.put("code", companyCode);
        map2.put("username", company.getPhoneNumber());
        map2.put("pwd", "123456");
        return map2;
    }

    @ApiOperation(value = "注册公司发送验证码", notes = "注册公司发送验证码")
    @GetMapping("/companys/verifyCode")
    public void verificationCode(@RequestParam("phone") @ApiParam(value = "手机号码") String phone) {
        String verifyCode = baseCompanyService.SmsVerificationCode(phone);
        if (!StringUtils.isEmpty(verifyCode)) {
            baseCompanyService.saveVerifyCode(phone, verifyCode);
        }
    }


    public String hexpwd(String pwd, String npwd) {
        String salt = UUID.randomUUID().toString().substring(0, 6);
        System.out.println(SHA256Util.getSHA256StrJava("G1" + salt + pwd).length());//G1+随机数+密码进行SHA256运算
        Random random = new Random();
        int cycletimes = (int) (random.nextInt(100)) + 100;//后随机数范围变成[ 100~199）；循环次数
        System.out.println(cycletimes);
        String sh256 = "";
        sh256 = SHA256Util.getSHA256StrJava("G1" + salt + pwd);//G1+随机数+密码进行SHA256运算 循环多少次循环的次数是随机生成的
        for (int i = 0; i <= cycletimes; i++) {
            sh256 = SHA256Util.getSHA256StrJava("G1" + salt + pwd + sh256);//G1+yan+密码进行SHA256运算 循环多少次循环的次数是随机生成的
            sh256 = sh256;
            //sh256=SHA256Util.getSHA256StrJava("G1"+cd+"123456");
            //System.out.println(sh256);
        }
        System.out.println(sh256);
        String hex = HexStringUtils.toHex("G1" + salt + cycletimes + sh256);//16进制字符串
        System.out.println("16进制字符串存数据库" + hex);
        return hex;
    }

}


